package com.yjy.fuyao.stu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjy.fuyao.stu.entity.Subject;
import com.yjy.fuyao.stu.entity.SubjectTree;
import com.yjy.fuyao.stu.entity.dto.ExcelSubjectDTO;
import com.yjy.fuyao.stu.listener.ExcelSubjectDTOListener;
import com.yjy.fuyao.stu.mapper.SubjectMapper;
import com.yjy.fuyao.stu.service.SubjectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author yjy
 * @since 2021-08-15
 */
@Slf4j
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Resource
    private SubjectMapper subjectMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream, ExcelSubjectDTO.class,new ExcelSubjectDTOListener(subjectMapper)).sheet().doRead();
        log.info("读取成功");
    }

    @Override
    public List<ExcelSubjectDTO> exportData() {
        List<Subject> subjects = subjectMapper.selectList(null);
        ArrayList<ExcelSubjectDTO> excelSubjectDTOS = new ArrayList<>(subjects.size());
        subjects.forEach(subject -> {
            ExcelSubjectDTO excelSubjectDTO = new ExcelSubjectDTO();
            BeanUtils.copyProperties(subject,excelSubjectDTO);
            excelSubjectDTOS.add(excelSubjectDTO);
        });
        return excelSubjectDTOS;
    }

    @Override
    public List<Subject> listByParentId(Long parentId) {
        List<Subject> subjects = null;
        //先在redis中取数据
        try {
            log.info("redis中取数据");
            subjects = (List<Subject>) redisTemplate.opsForValue().get("fuyao:stu:subjects:" + parentId);
            //如果成功直接返回
            if(subjects != null){
                log.info("redis中返回数据");
                return subjects;
            }
        } catch (Exception e) {
            log.error("redis服务器异常:"+ ExceptionUtils.getStackTrace(e));
        }
        //否则进行数据库取数据
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        System.out.println("parentId======================"+parentId);
        queryWrapper.eq("parent_id",parentId);
        subjects = subjectMapper.selectList(queryWrapper);
        subjects.forEach(subject -> {
            subject.setHasChildren(hasChildren(subject.getId()));
        });
        try {
            //将取出的数据放到redis中
            log.info("redis中保存数据");
            redisTemplate.opsForValue().set("fuyao:stu:subjects:" + parentId,subjects,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务器异常:"+ExceptionUtils.getStackTrace(e));
        }
        System.out.println("subjects:===================="+subjects);
        return subjects;
    }

    @Override
    public List<SubjectTree> listAll() {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",0);
        List<Subject> subjects = baseMapper.selectList(queryWrapper);
        List<SubjectTree> treeList = new ArrayList<>();
        for (Subject subject:subjects) {
            QueryWrapper<Subject> qw = new QueryWrapper<>();
            System.out.println("parent_id================>>>>"+subject.getId());
            qw.eq("parent_id",subject.getId());
            List<Subject> subChildren = baseMapper.selectList(qw);
            List<SubjectTree> treeChildList = new ArrayList<>();
            for (Subject child:subChildren) {
                SubjectTree treeChild = new SubjectTree();
                treeChild.setId(child.getId());
                treeChild.setTitle(child.getTitle());
                treeChildList.add(treeChild);
            }
            SubjectTree tree = new SubjectTree();
            tree.setId(subject.getId());
            tree.setTitle(subject.getTitle());
            tree.setChildren(treeChildList);
            treeList.add(tree);
        }
        return treeList;
    }

    public Boolean hasChildren(String parentId){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        int count = subjectMapper.selectCount(queryWrapper);
        return count > 0;
    }

}
